<template>
  <el-dialog
    v-model="renderVisible"
    title="添加快递信息"
    width="360px"
    append-to-body
    destroy-on-close
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div>
      <el-form ref="formRef" :model="formData" :rules="formRules">
        <el-form-item label="快递公司" prop="platform">
          <el-select v-model="formData.platform" style="width: 100%">
            <el-option
              v-for="item in dataListPlatform"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="orderNo">
          <el-input
            v-model="formData.orderNo"
            :maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="renderVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClickSubmit(formRef)"
          >添加</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { ElForm } from 'element-plus';
import { getPlatformList } from '@/utils/common';

// 表单 - ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 快递公司
const dataListPlatform = getPlatformList();

// 表单数据
const GetFormData = (): API.logistics.EntityDto => ({
  platform: '其他快递',
  orderNo: Math.floor(Math.random() * 10000000).toString(16)
});
const formData = ref(GetFormData());

// 表单 - 验证
const formRules = reactive({
  platform: [{ required: true, trigger: 'blur', message: '请输入' }],
  orderNo: [{ required: true, trigger: 'blur', message: '请输入' }]
});

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: {
    type: String,
    default: '编辑规格'
  },

  size: {
    type: [String, Number],
    default: '50%'
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onComplete']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// 初始化数据
const initPageData = () => {
  // 还原数据
  formData.value = GetFormData();
};

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;
    initPageData();
  },
  {
    immediate: true
  }
);

// btn - submit
const handleClickSubmit = async (
  formEl: InstanceType<typeof ElForm> | undefined
) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;

    emits('onComplete', {
      action: 'submit',
      // 返回新数据
      result: { ...formData.value }
    });
    renderVisible.value = false;
  });
};
</script>

<style lang="scss" scoped></style>
